# -*- coding: utf-8 -*-
from datetime import datetime

from common.stats import MG_BIGBANG_COLL as mg
from common.account.db.account import get_account
from common.utils.decorator import mongo_wrapper
from common.stats.helper import list_object


@mongo_wrapper
def create_device_track(info):
    """
        params: {
            "aid": 'xxxxxxxxxxxx', # android device id
            "type": 'htc',         # android machine brand,
            "run_count": 10,       # app open count,
            "uid":  123456,         # ignore...
            "reason": [],           # reason
        }
        extra need data: {
            "created_at": '2016-06-20 10:00:00', # first run time for this aid
            "remove_at": '2016-06-21 10:00:00',  # last uninstall time
            "total_pay": 0,                      # sum pay.total of user_stats
            "ucount": 5,                          # this aid total user count
            "uid": 1                            # the uid pay most
        }
    """
    info['remove_at'] = datetime.utcnow()
    stats = {}
    aid = info.pop('aid')
    stats = mg.user_stats.aggregate([
        {'$match': {'aid': aid}},
        {'$group': {'_id': None, 'count': {'$sum': 1},
                    'total': {'$sum': '$pay.total'}}}
    ])
    stats = stats.next() if stats.alive else {}
    info['total_pay'] = stats.get('total', 0)
    info['ucount'] = stats.get('count', 0)
    if info['ucount'] > 0:
        t = mg.user_stats.find({'aid': aid}).sort('pay.total', -1).limit(1)
        t = t[0]
        info['uid'] = t['_id']
    mg.device_stats.update({'_id': aid}, {'$set': info}, upsert=True)
    k = mg.device_stats.find_one({'_id': aid})
    if 'created_at' not in k:
        calc_info = {}
        if 'created_at' in stats:
            calc_info['created_at'] = stats['created_at']
        elif 'uid' in info:
            account = get_account(info['uid'])
            if account is not None:
                calc_info['created_at'] = account.created_at
        if not calc_info:
            calc_info['created_at'] = info['remove_at']
        mg.device_stats.update({'_id': aid}, {'$set': calc_info})


@mongo_wrapper
def update_uninstall_reason(info):
    aid = info.pop('aid')
    mg.device_stats.update({'_id': aid}, {'$set': info}, upsert=True)


@mongo_wrapper
def list_device_stats(query_dct):
    return list_object(query_dct, mg.device_stats)


@mongo_wrapper
def calc_questionare_overview(min_date, max_date):
    filters = {'reason': {'$exists': True}}
    if min_date:
        filters.setdefault('remove_at', {})['$gte'] = min_date
    if max_date:
        filters.setdefault('remove_at', {})['$lt'] = max_date
    if not filters:
        filters = {'remove_at': {'$exists': True}}
    info = {
        'total_count': mg.device_stats.count(filters),
        'dist': {}
    }
    for k in range(1, 11):
        filters['reason'] = str(k)
        info['dist'][k] = mg.device_stats.count(filters)
    return info


@mongo_wrapper
def calc_uninstall_overview(min_date, max_date):
    info = {
        'total_count': 0,
        'run_count': 0,
        'pay_count': 0
    }
    filters = {}
    if min_date:
        filters.setdefault('remove_at', {})['$gte'] = min_date
    if max_date:
        filters.setdefault('remove_at', {})['$lt'] = max_date
    if not filters:
        filters = {'remove_at': {'$exists': True}}
    info['total_count'] = mg.device_stats.count(filters)
    filters['total_pay'] = {'$gt': 0}
    info['pay_count'] = mg.device_stats.count(filters)

    temp = mg.device_stats.aggregate([
        {'$match': {'remove_at': filters['remove_at']}},
        {'$group': {'_id': None, 'total': {'$sum': '$run_count'}}}])
    temp = temp.next() if temp.alive else {}
    info['run_count'] = temp.get('total', 0)

    return info
